package org.linlinjava.litemall.core.util;

import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

@Service
public class RedisUntil {

	@Resource
	private  RedisTemplate<String, Object> redisTemplate;
	@Autowired
	private StringRedisTemplate redis;

	public void set(String key, Object value, long timeout) {
		ValueOperations<String, Object> vo = redisTemplate.opsForValue();
		vo.set(key, value, timeout, TimeUnit.SECONDS);
	}
  public void setSeconds(String key, Object value, long timeout) {
    ValueOperations<String, Object> vo = redisTemplate.opsForValue();
    vo.set(key, value, timeout, TimeUnit.SECONDS);
  }
	/*
	 * public void set(String key, Object value) { ValueOperations<String,
	 * Object> vo = redisTemplate.opsForValue(); vo.set(key, value); }
	 */

	public Object get(String key) {
		ValueOperations<String, Object> vo = redisTemplate.opsForValue();
		return vo.get(key);
	}

	public void setAddStr(String key,String str){
     redisTemplate.opsForValue().append(key,str);
  }
	
	public void delete(String key) {
		redisTemplate.delete(key);
	}
	public Set<String> getLikeKey(String prefix){
		Set<String> keys = redisTemplate.keys(prefix+ "*");
		return keys;
	}
	public void deleteLikeKey(String prefix) {
		Set<String> keys = redisTemplate.keys(prefix+ "*");
		redisTemplate.delete(keys);
	}
  @Autowired(required = false)
  public void setRedisTemplate(RedisTemplate redisTemplate) {
    RedisSerializer stringSerializer = new StringRedisSerializer();//序列化为String
    //Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);//序列化为Json
    redisTemplate.setKeySerializer(stringSerializer);
    //redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
    //redisTemplate.setHashKeySerializer(stringSerializer);
    //redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
    this.redisTemplate = redisTemplate;
  }

	
}
